package com.uin.saas.dbconfig;

import com.uin.saas.dao.MasterTenantDao;
import com.uin.saas.entity.MasterTenant;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;

/**
 * Created with IDEA
 *
 * @author : zhoupan
 * @date : 2019/4/9 10:53
 * @info :
 */
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("execution(* com.uin.saas.controller.*.*(..))")
    private void pointcut() {

    }
    @Autowired
    private DynamicDataSource dynamicDataSource;
    @Autowired
    private MasterTenantDao masterTenantDao;



    @Before("pointcut()")
    public void beforeSwitchDS(JoinPoint point) throws Exception {
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if (request.getHeader("saas")!=null) {
            List<MasterTenant> masters = masterTenantDao.selectList(null);
            MasterTenant masterTenant = masters.get(0);
            String dataSource = masterTenant.getTenant();
            dynamicDataSource.createDataSourceWithCheck(masterTenant);
            DBContextHolder.setDataSource(dataSource);
        }
//        //获得当前访问的class
//        Class<?> className = point.getTarget().getClass();
//        //获得访问的方法名
//        String methodName = point.getSignature().getName();
//        Object[] objects=point.getArgs();
//        //得到方法的参数的类型
//        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
//        String dataSource = masterTenant.getTenant();
//        try {
//            // 得到访问的方法对象
//            Method method = className.getMethod(methodName, argClass);
//            Parameter[] parameters = method.getParameters();
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            // 切换数据源
//            DBContextHolder.setDataSource(dataSource);
//        }
    }

    @After("pointcut()")
    public void afterSwitchDS(JoinPoint point){

        DBContextHolder.clearDataSource();

    }

}
